#include "PlatformProperty.h"

#include <math.h>

SYSTEM_READ_WRITE_PROPERTY(DOOR_POS, int32_t) {
    // [SW_FC_009_035] Vehicle 两盖-电动尾门实时位置
    builder.area(VehicleAreaDoor::REAR)
            .initValue([]() {
            return 95;
        })
        .withStatusBySignals(
            []([[maybe_unused]] const PropertyStatus& last) {
                auto carmod = SIGNAL.getVehModMngtGlbSafe1CarModSts1();
                auto usgmod = SIGNAL.getVehModMngtGlbSafe1UsgModSts();
                auto cc98 = SIGNAL.getcarconfig98();
                VHALOG.d(
                    "DOOR_POS status Change carmod[%d], "
                    "usgmod[%d], cc98[%d]",
                    carmod, usgmod, cc98);
                if (!SIGNAL.carConfigIs(SignalRX::carconfig98, sdb::CarConfig98::_01)) {
                    if (!SIGNAL.usgModeIs(sdb::UsgModSts1::UsgModAbdnd) &&
                        SIGNAL.carModeIs(sdb::CarModSts1::CarModNorm, sdb::CarModSts1::CarModFcy,
                                         sdb::CarModSts1::CarModCrash,
                                         sdb::CarModSts1::CarModDyno)) {
                        return PropertyStatus::Active;
                    }
                    return PropertyStatus::NotActive;
                }
                return PropertyStatus::NotAvailable;
            },
            SignalRX::VehModMngtGlbSafe1UsgModSts, SignalRX::VehModMngtGlbSafe1CarModSts1,
            SignalRX::carconfig98)
        .withValueBySignals(
            []([[maybe_unused]] const int32_t& last) {
                int32_t posn = SIGNAL.getTrOpenPosn();
                VHALOG.d(
                    "DOOR_POS Value Change last:[%d], cur:[%d]",
                    last, posn);
                return posn;
            },
            SignalRX::TrOpenPosn)
        .onSetProperty([this](const int32_t& value) {
            int32_t step = LCFG.getInt<int32_t>(lcfg::LCFG_OperateTailgatePositionStep);
            int32_t curValue = getValue(static_cast<int32_t>(VehicleAreaDoor::REAR));

            VHALOG.d("DOOR_POS : cur[%d] value[%d] step[%d]", curValue, value, step);
            if (abs(value - curValue) <= step) {
                VHALOG.d("DOOR_POS : less then step, no need to set");
                return;
            }

            if (value < 0 || value > 100) {
                VHALOG.d("DOOR_POS : param invaild");
                return;
            }

            if (value < 11) {
                SIGNAL.setTrOpenPosnReqFromHmi(0);
            } else if (value < 96) {
                SIGNAL.setTrOpenPosnReqFromHmi(value);
            } else {
                SIGNAL.setTrOpenPosnReqFromHmi(95);
            }

            if (!SIGNAL.usgModeIs(sdb::UsgModSts1::UsgModAbdnd)) {
                VHALOG.d("DOOR_POS : setCB_VFC_SetVehMisc");
                SIGNAL.setCB_VFC_SetVehMisc(sdb::OnOff1::On);
            }
        });
}